<template>
  <div class="app-container">

    <el-form :inline="true" class="demo-form-inline filter">
    <div>
      <el-form-item v-if="this.$store.state.user.fsiteLevel==3" label="客户名称">
         <el-select disabled v-model="listQuery.fsiteNo" clearable filterable class="filter-item" placeholder="请选择客户名称">
        <el-option
          v-for="item in fsiteNoBelongOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>
      </el-form-item>
       <el-form-item v-else label="客户名称">
         <el-select v-model="listQuery.fsiteNo" clearable filterable class="filter-item" placeholder="请选择客户名称" @change="getFpointOptions(listQuery.fsiteNo)">
        <el-option
          v-for="item in fsiteNoBelongOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>
      </el-form-item>
      <el-form-item label="教室">
        <el-select v-model="listQuery.fpointNo" clearable filterable class="filter-item" placeholder="请选择教室">
        <el-option
          v-for="item in fpointOptions"
          :key="item.fpointNo"
          :label="item.fpointName"
          :value="item.fpointNo"/>
      </el-select>
      </el-form-item>
      <el-form-item label="课程">
        <el-select v-model="listQuery.fcourseno" clearable filterable class="filter-item" placeholder="请选择课程">
        <el-option
          v-for="item in fcoursenoOptions"
          :key="item.fcourseno"
          :label="item.fcoursename"
          :value="item.fcourseno"/>
      </el-select>
      </el-form-item>
         <el-form-item label="老师">
        <el-select v-model="listQuery.fuserid" clearable filterable class="filter-item" placeholder="请选择老师">
        <el-option
          v-for="item in fuseridOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"/>
      </el-select>
      </el-form-item>
    </div>
    <div>
       <el-form-item class="onlyDate" label="课程日期">
        <el-date-picker placeholder="请选择日期" v-model="listQuery.fclassdate" type="date"/>
      </el-form-item>
      <el-form-item>
        <el-button round size="medium" class="filter-item" :style="{background:buttonColor.lookup,color:buttonColor.color}" @click="handleFilter">查找</el-button>
        <el-button round size="medium" class="filter-item" :style="{background:buttonColor.add ,color:buttonColor.color}" @click="handleCreate">添加</el-button>
        <el-button round size="medium" :style="{background:buttonColor.import,color:buttonColor.color}" @click="handleUpload">导入</el-button>
      </el-form-item>
    </div>
    </el-form>
      <!-- <el-date-picker v-model="listQuery.fclassdate" type="datetime" placeholder="请输入上课日期"></el-date-picker>
      <el-input v-model="listQuery.fbegtime" clearable class="filter-item" style="width: 200px;" placeholder="请输入上课时间"/>
      <el-input v-model="listQuery.fendtime" clearable class="filter-item" style="width: 200px;" placeholder="请输入下课时间"/>
        <el-input v-model.number="listQuery.fstate" clearable class="filter-item" style="width: 200px;" placeholder="请输入课程状态"/> -->

    <!-- 查询结果 -->
    <el-table :height="buttonColor.clientHeightTwo" v-loading="listLoading" :data="list" stripe element-loading-text="正在查询中。。。" border fit highlight-current-row :header-cell-style="tableColor">
        <el-table-column :width="buttonColor.operationTwo" align="center" label="操作" class-name="small-padding">
        <template slot-scope="scope">
           <div class="operationButton">
            <div :style="{color:buttonColor.edit,cursor:'pointer'}" @click="handleUpdate(scope.row)">
            <img src="../../../public/images/edit.png" />
            编辑
          </div>
          <div :style="{color:buttonColor.delete,cursor:'pointer'}" @click="handleDelete(scope.row)">
            <img src="../../../public/images/del.png" />
            删除
          </div>
          </div>
        </template>
      </el-table-column>
      <el-table-column :width="buttonColor.line" :index="indexMethod" align="center" label="序" type="index" />
      <el-table-column :formatter="formatSite" align="left" label="客户名称" prop="fsiteNo"/>
      <el-table-column :formatter="formatfpointNo" width="150" align="left" label="教室" prop="fpointNo" />
      <el-table-column :formatter="formatfcourseno" align="left" label="课程" prop="fcourseno" />
      <el-table-column :formatter="formatfuserid" align="left" label="上课老师" prop="fuserid" />
      <el-table-column :formatter="datetimeFormat" width="110" align="left" label="上课日期" prop="fclassdate" />
      <el-table-column align="left" width="110" label="上课时间" prop="fbegtime" />
      <el-table-column align="left" width="110" label="下课时间" prop="fendtime" />
      <el-table-column align="left" :width="buttonColor.state" label="课程状态" prop="fstate">
        <template slot-scope="scope">
          <span :style="{color:buttonColor.statedisable}" v-if="scope.row.fstate==0">{{ scope.row.fstate | statusFilter }}</span>
          <span :style="{color:buttonColor.statestart}" v-else>{{ scope.row.fstate | statusFilter }}</span>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-dialog :close-on-click-modal="false" :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <template slot="title">
        <div :style="titleColor">{{textMap[dialogStatus]}}</div>
      </template>
      <el-form ref="dataForm" :rules="rules" :model="dataForm" status-icon label-position="left" label-width="90px">
        <el-row>
          <el-col :span="12">
             <el-form-item class="required" v-if="this.$store.state.user.fsiteLevel==3" label="客户名称" prop="fsiteNo">
              <el-select v-model="dataForm.fsiteNo" disabled clearable filterable placeholder="请选择" @change="getStations(dataForm.fsiteNo, true)">
                <el-option
                  v-for="item in fsiteNoBelongOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
            <el-form-item v-else class="required" label="客户名称" prop="fsiteNo">
              <el-select v-model="dataForm.fsiteNo" :disabled="dialogStatus=='update'" clearable filterable placeholder="请选择" @change="getStations(dataForm.fsiteNo, true)">
                <el-option
                  v-for="item in fsiteNoBelongOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
             <el-form-item class="required" label="教室" prop="fpointNo">
                <el-select v-model="dataForm.fpointNo" clearable filterable class="filter-item" placeholder="请选择教室">
                <el-option
                  v-for="item in fpointOptionsAdd"
                  :key="item.fpointNo"
                  :label="item.fpointName"
                  :value="item.fpointNo.toString()"/>
              </el-select>
              </el-form-item>
          </el-col>
        </el-row>
         <el-row>
          <el-col :span="12">
             <el-form-item class="required" label="课程" prop="fcourseno">
                <el-select v-model="dataForm.fcourseno" clearable filterable class="filter-item" placeholder="请选择课程">
                <el-option
                  v-for="item in fcoursenoOptions"
                  :key="item.fcourseno"
                  :label="item.fcoursename"
                  :value="item.fcourseno"/>
              </el-select>
              </el-form-item>
          </el-col>
          <el-col :span="12">
              <el-form-item class="el-form-item-small" label="课程状态" prop="fstate">
              <el-select v-model="dataForm.fstate" class="filter-item" placeholder="请选择课程状态">
                <el-option v-for="(key, value) in statusMap" :key="key" :label="key" :value="value"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
         <el-row>
          <el-col :span="12">
            <el-form-item class="required" label="老师" prop="fuserid">
              <el-select v-model="dataForm.fuserid" clearable filterable class="filter-item" placeholder="请选择老师">
              <el-option
                v-for="item in fuseridOptionsAdd"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="required" label="上课日期" prop="fclassdate">
              <el-date-picker placeholder="请选择上课日期" v-model="dataForm.fclassdate" type="date" :picker-options="pickerOptions"/>
            </el-form-item>
          </el-col>
        </el-row>
         <el-row>
          <el-col :span="12">
            <el-form-item class="required" label="上课时间" prop="fbegtime">
              <!-- <el-time-picker placeholder="请选择上课时间" v-model="dataForm.fbegtime"/> -->
              <el-time-select
              v-model="dataForm.fbegtime"
              :picker-options="{
                start: '00:00',
                step: '00:15',
                end: '23:30'
              }"
              placeholder="选择时间上课时间">
            </el-time-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item class="required" label="下课时间" prop="fendtime">
              <!-- <el-time-picker placeholder="请选择下课时间" v-model="dataForm.fendtime"/> -->
              <el-time-select
              v-model="dataForm.fendtime"
              :picker-options="{
                start: '00:00',
                step: '00:15',
                end: '23:30'
              }"
              placeholder="选择时间下课时间">
            </el-time-select>
            </el-form-item>
          </el-col>
        </el-row>
         <el-row>
          <el-col :span="24">
            <el-form-item class="text" style="width:93%" label="描述" prop="fnote">
              <el-input v-model="dataForm.fnote"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button round :style="{background:buttonColor.cancel,color:buttonColor.colorone}" @click="dialogFormVisible = false">取消</el-button>
        <el-button round v-if="dialogStatus=='create'" :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="createData">确定</el-button>
        <el-button round v-else :style="{background:buttonColor.confirm,color:buttonColor.color}" @click="updateData">确定</el-button>
      </div>
    </el-dialog>
     <!-- 导出弹窗 -->
    <el-dialog width="auto" :close-on-click-modal="false" :visible.sync="uploadVisible">
       <template slot="title">
      <div :style="exportColor">课程表</div>
    </template>
      <div style="width:300px;height:200px;display: flex;flex-direction: column;align-items: center">
          <el-upload
          :on-success="uploadFileSuccess"
          :headers="headers"
          :action="uploadPath2"
          :data="{'tableName':'import_i_ts_tcCourse'}"
          :show-file-list="false"
          class="filter-item"
          style="margin-top:20px"
          accept=".xlsx">
          <el-button round size="medium" icon="el-icon-upload" :style="{background:buttonColor.import,color:buttonColor.color}">导入</el-button>
        </el-upload>
        <div style="margin-top:30px;text-decoration:underline">
          <a :href="downUrl" style="color: blue">模板文件下载</a>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<style>
  .button-margin {
    margin : 2px 0px;
  }
  .el-button+.el-button {
    margin-left: 1px;
  }
</style>

<script>
import { listtcCourse, createtcCourse, updatetcCourse, deletetcCourse } from '@/api/tcCourse'
import Pagination from '@/components/Pagination'
import moment from 'moment'
import { fsiteOptionsByLevel,getListArea } from '@/api/area'
import { listRoom} from '@/api/room'
import { listtsCourse} from '@/api/tsCourse'
import { listAdmin } from '@/api/admin'
import { uploadPath2 } from "@/api/area"
import { getToken } from '@/utils/auth'
import { getApiUrl } from '@/utils/request'
import { tableColor,titleColor,buttonColor,exportColor } from '@/filters/index'

const statusMap = {
  0: '禁用',
  1: '启用'
}

export default {
  name: 'STcCourse',
  components: { Pagination },
  filters: {
    statusFilter(type) {
      return statusMap[type]
    }
  },
  data() {
    return {
      userAll: [],
      roomAll: [],
      statusMap,
      uploadPath2,
      exportColor,
      buttonColor,
      titleColor,
      tableColor,
      fpointOptionsAdd:[],
      fuseridOptionsAdd: [],
      fuseridOptions: [],
      fcoursenoOptions: [],
      fpointOptions: [],
      fsiteNoBelongOptions: [],
      uploadVisible: false,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        fsiteNo: undefined,
        fpointNo: undefined,
        fcourseno: undefined,
        fuserid: undefined,
        fclassdate: undefined,
        fbegtime: undefined,
        fendtime: undefined,
        fnote: undefined,
        fstate: undefined,
        fupddate: undefined,
        foperator: undefined,
        sort: 'create_time',
        order: 'desc'
      },
      dataForm: {
        fsiteNo: undefined,
        fpointNo: undefined,
        fcourseno: undefined,
        fuserid: undefined,
        fclassdate: undefined,
        fbegtime: undefined,
        fendtime: undefined,
        fnote: undefined,
        fstate: undefined,
        fupddate: undefined,
        foperator: undefined,
        id: undefined
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        fsiteNo: [
          { required: true, message: '所属客户不能为空' },
        ],
        fpointNo: [
          { required: true, message: '教室编号不能为空' },
        ],
        fcourseno: [
          { required: true, message: '课程编号不能为空' },
        ],
        fuserid: [
          { required: true, message: '上课老师不能为空' },
          { type: 'number', message: '上课老师必须为数字值' },
        ],
        fclassdate: [
          { required: true, message: '上课日期不能为空' },
        ],
        fbegtime: [
          { required: true, message: '上课时间不能为空' },
        ],
        fendtime: [
          { required: true, message: '下课时间不能为空' },
        ],
      },
       pickerOptions: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          },
        },
    }
  },
  computed: {
    headers() {
      return {
        'Authorization': getToken()
      }
    }
  },
  created() {
    this.downUrl = getApiUrl() + 'xlsx/1-7实验楼.xlsx'
    let temp = moment(new Date()).format('YYYY-MM-DD') + ' ' + '00:00:00'
    this.listQuery.fclassdate = new Date(temp)
    if(this.$store.state.user.fsiteLevel==3){
      this.listQuery.fsiteNo=this.$store.state.user.fsiteNo
      this.getStations(this.$store.state.user.fsiteNo)
      this.getFpointOptions(this.$store.state.user.fsiteNo)
       // 教室
      listRoom({fsiteNo: this.$store.state.user.fsiteNo,fpointFlag:0,fpointState: 2})
        .then(response => {
          this.roomAll = response.data.data.list
        })
        .catch(() => {
          this.roomAll = []
      })
    }else{
       // 教室
      listRoom({fpointFlag:0,fpointState: 2,limit: -1})
        .then(response => {
          this.roomAll = response.data.data.list
        })
        .catch(() => {
          this.roomAll = []
      })
    }
    this.getList()
    // 客户
     fsiteOptionsByLevel(3)
      .then(response => {
        this.fsiteNoBelongOptions = response.data.data.list
      })
      .catch(() => {
        this.fsiteNoBelongOptions = []
      })

      // 课程
      listtsCourse({limit: -1})
        .then(response => {
          this.fcoursenoOptions = response.data.data.list
        })
        .catch(() => {
          this.fcoursenoOptions = []
      })

      // 老师
      getListArea({flag: 8,arg1:11})
        .then(response => {
          this.userAll = response.data.data.list
        })
        .catch(() => {
          this.userAll = []
      })
  },
  methods: {
    // 导入
     uploadFileSuccess: function(response) {
       this.uploadVisible = false
      this.$notify.success({
        title: '导入',
        dangerouslyUseHTMLString:true,
        message: response.data
      })
    },
    handleUpload(){
      this.uploadVisible = true
    },

    // 添加客户
    getStations(fsiteNo){
      if(fsiteNo){
        this.dataForm.fpointNo = ''
        this.dataForm.fuserid = ''
        this.getRoomAdd(fsiteNo)
        this.getUseridAdd(fsiteNo)
      }else{
        this.dataForm.fpointNo = ''
        this.dataForm.fuserid = ''
        this.fpointOptionsAdd = []
        this.fuseridOptionsAdd = []
      }
    },
     getRoomAdd(fsiteNo){
       // 教室
      listRoom({fsiteNo: fsiteNo,fpointFlag:0,fpointState: 2})
        .then(response => {
          this.fpointOptionsAdd = response.data.data.list
        })
        .catch(() => {
          this.fpointOptionsAdd = []
      })
    },
     getUseridAdd(fsiteNo){
       // 老师
      getListArea({flag: 8,arg1:11,arg2: fsiteNo})
        .then(response => {
          this.fuseridOptionsAdd = response.data.data.list
        })
        .catch(() => {
          this.fuseridOptionsAdd = []
      })
    },

    // 查询客户
    getFpointOptions(fsiteNo){
      if(fsiteNo){
        this.listQuery.fpointNo = ''
        this.listQuery.fuserid = ''
        this.getRoom(fsiteNo)
        this.getUserid(fsiteNo)
      }else{
        this.listQuery.fpointNo = ''
        this.listQuery.fuserid = ''
        this.fpointOptions = []
        this.fuseridOptions = []
      }
    },
    getRoom(fsiteNo){
       // 教室
      listRoom({fsiteNo: fsiteNo,fpointFlag:0,fpointState: 2})
        .then(response => {
          this.fpointOptions = response.data.data.list
        })
        .catch(() => {
          this.fpointOptions = []
      })
    },
     getUserid(fsiteNo){
       // 老师
      getListArea({flag: 8,arg1:11,arg2: fsiteNo})
        .then(response => {
          this.fuseridOptions = response.data.data.list
        })
        .catch(() => {
          this.fuseridOptions = []
      })
    },
    // 客户
    formatSite: function(row, column) {
      if(this.fsiteNoBelongOptions){
        for (let i = 0; i < this.fsiteNoBelongOptions.length; i++) {
        if (row.fsiteNo === this.fsiteNoBelongOptions[i].value) {
          return this.fsiteNoBelongOptions[i].label
        }
      }
      return ''
      }else{
        return ''
      }
    },
    // 教室
    formatfpointNo: function(row, column) {
      if(this.roomAll){
        for (let i = 0; i < this.roomAll.length; i++) {
        if (row.fpointNo === this.roomAll[i].fpointNo) {
          return this.roomAll[i].fpointName
        }
      }
      return ''
      }else{
        return ''
      }
    },
    // 课程
      formatfcourseno: function(row, column) {
      if(this.fcoursenoOptions){
        for (let i = 0; i < this.fcoursenoOptions.length; i++) {
        if (row.fcourseno === this.fcoursenoOptions[i].fcourseno) {
          return this.fcoursenoOptions[i].fcoursename
        }
      }
      return ''
      }else{
        return ''
      }
    },
    //老师
    formatfuserid: function(row, column) {
      if(this.userAll){
        for (let i = 0; i < this.userAll.length; i++) {
        if (row.fuserid === this.userAll[i].value) {
          return this.userAll[i].label
        }
      }
      return ''
      }else{
        return ''
      }
    },
    datetimeFormat(row, column) {
      const date = row[column.property]
      if (date === undefined || date === null) {
        return ''
      }
      return moment(date).format('YYYY-MM-DD')
    },
     formatDate: function(date) {
      if(typeof(date)==='object'){
         var ym
      var y = date.getFullYear()
      var m = date.getMonth() + 1
      var d = date.getDate()
      if (m < 10) {
        m = '0' + m
      }
      if (d < 10) {
        d = '0' + d
      }
      ym = '' + y + '-' + m + '-' + d
      return ym
      }else{
        return date
      }
    },

    dateFormat(date) {
        //日期格式化
        var d = new Date(date)
        let year = d.getFullYear()
        let month = d.getMonth() + 1
        month = '0' + month
        month = month.substring(month.length - 2)
        let day = '0' + d.getDate()
        day = day.substring(day.length - 2)
        let hour = '0' + d.getHours()
        hour = hour.substring(hour.length - 2)
        let m = '0' + d.getMinutes()
        m = m.substring(m.length - 2)
        let s = '0' + d.getSeconds()
        s = s.substring(s.length - 2)
        let format = hour + ':' + m
        return format
      },
    getList() {
      this.listLoading = true
      listtcCourse(this.listQuery)
        .then(response => {
          this.list = response.data.data.list
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    resetForm() {
      this.dataForm = {
        fsiteNo: undefined,
        fpointNo: undefined,
        fcourseno: undefined,
        fuserid: undefined,
        fclassdate: undefined,
        fbegtime: undefined,
        fendtime: undefined,
        fnote: undefined,
        fstate: undefined,
        fupddate: undefined,
        foperator: undefined,
        id: undefined
      }
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      // this.dataForm.fclassdate = new Date()
      this.dataForm.fstate = "1"
       if(this.$store.state.user.fsiteLevel !=3){
          this.fuseridOptionsAdd = []
          this.fpointOptionsAdd = []
       }
      if(this.$store.state.user.fsiteLevel==3){
        this.dataForm.fsiteNo=this.$store.state.user.fsiteNo
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dataForm.foperator=this.$store.state.user.id
          this.dataForm.fupddate=new Date()
          // this.dataForm.fbegtime = this.dateFormat(this.dataForm.fbegtime)
          // this.dataForm.fendtime = this.dateFormat(this.dataForm.fendtime)
          createtcCourse(this.dataForm)
            .then(response => {
              this.list.unshift(response.data.data)
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '添加上课表成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response
              })
            })
        }
      })
    },
    handleUpdate(row) {
      if(this.$store.state.user.fsiteLevel !=3){
        this.getStations(row.fsiteNo)
     }
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.dataForm.fstate = row.fstate.toString()
       let temp = moment(row.fclassdate).format('YYYY-MM-DD')+ ' '
      // this.dataForm.fbegtime = temp.concat(row.fbegtime ,':00')
      // this.dataForm.fendtime = temp.concat(row.fendtime,':00')
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.dataForm.foperator=this.$store.state.user.id
          this.dataForm.fupddate=new Date()
          // this.dataForm.fbegtime = this.dateFormat(this.dataForm.fbegtime)
          // this.dataForm.fendtime = this.dateFormat(this.dataForm.fendtime)
          updatetcCourse(this.dataForm, this.$route.query.id)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新上课表成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: response
              })
            })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('是否要删除此课程管理', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deletetcCourse(row)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除课程管理成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response
            })
          })
      })
    },
    indexMethod(index) {
      index = index + 1
      return index
    }
  }
}
</script>
